﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using verk2013_project_group12.Filters;
using verk2013_project_group12.Models;

namespace verk2013_project_group12.Controllers
{
    [Authorize]
    public class AdminController : Controller
    {
        //
        // GET: /Admin/

        /*
         This controller is almost identical to the homecontroller. The only difference is the ban function.
          */
        [HttpGet]
        public ActionResult Index()
        {
            NewsRepository news = new NewsRepository();
            var getAllNews = news.GetAllNews();
            var allNews = from i in getAllNews
                         .OrderByDescending(i => i.ID)
                         .Take(3)
                          select i;

            return View(allNews);
        }

        [HttpPost]
        [InitializeSimpleMembership]
        public ActionResult Index(FormCollection formData)
        {
            string newsTitle = formData["NewsTitle"];
            string newsText = formData["NewsText"];

            NewsItem news = new NewsItem();
            NewsRepository newsRep = new NewsRepository();
            news.Title = newsTitle;
            news.Content = newsText;
            
            newsRep.Add(news);
            newsRep.Save();

            return RedirectToAction("Index");
        }

        public ActionResult PlayerList()
        {
            UserRepository users = new UserRepository();
            var allUsers = users.GetAllUsers();
            return View(allUsers);

        }

        public ActionResult profile(int? id)
        {
            if (id != null)
            {
                UserRepository users = new UserRepository();
                var user = users.GetUserById(id.Value);
                if (user != null)
                {
                
                    return View(user);
                }
                else
                {
                    return View("Error");
                }
            }
            else
            {
                return View("Error");
            }
        }


        [HttpPost]
        public ActionResult banPlayer(string username)
        {
            /* This is the only function that is diffirent form the homecontroller.
               This function allows the admin to ban other user and remove them from them database.
             */
            UserRepository rep = new UserRepository();
            UserProfile user = rep.GetUserByUsername(username);

            rep.DeleteUser(user);
            rep.Save();
           
            IEnumerable<UserProfile> users = rep.GetAllUsers();
            return Json(users, JsonRequestBehavior.AllowGet);
            // The function return json object.
        }

    }
}
